<template>
	<view class="chatInterface">
		<view class="scroll-view">
			<view class="all-history-loaded">
				{{allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息'}}
			</view>
			<!--已经收到的消息-->
			<view v-for="(message,index) in messages" :key="message.messageId">
				<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
				<view class="time-lag">
					{{renderMessageDate(message, index)}}
				</view>
				<view class="message-item" :class="{'self' : message.senderId == (currentUser && currentUser.uuid)}">
					<view class="avatar"
						  v-if="message.senderId != (currentUser && currentUser.uuid)">
						<image :src="friend.avatar"></image>
					</view>
					<view class="avatar" v-else>
						<image :src="currentUser.avatar"></image>
					</view>
					<view class="content">
						<b class="pending" v-if="message.status == 'sending'"></b>
						<b class="send-fail" v-if="message.status == 'fail'"></b>
						<view v-if="message.type == 'text'" v-html="renderTextMessage(message)"></view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="action-box">
			<view class="action-top">
				<view class="message-input">
					<!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
					<input type="text" maxlength="300" placeholder="发送消息" v-model="content" @focus="messageInputFocusin" @confirm="sendTextMessage">
				</view>
				<span class="send-message-btn" @tap="sendTextMessage">发送</span>
			</view>
		</view>
	

	</view>
</template>

<script>
	import { mapState } from "vuex"
	export default {
		name: "privateChat",
		computed: {
			...mapState(['userInfo']),
		},
		data() {
			return {
				//聊天文本框
				content: '',
				friend: null,
				currentUser: null,
				//已经接收到的消息
				messages: [],
				//已经加载完所有历史消息
				allHistoryLoaded: false,
			}
		},
	
		onShow () {
	
		},
		onLoad(options) {
			this.currentUser = {
				"uuid": this.userInfo.id + '',
				// "uuid": '33c3693b-dbb0-4bc9-99c6-fa77b9eb763f',
				"name": this.userInfo.nickName,
				"avatar": this.getImgUrl(this.userInfo.avatar)
			}
            //从服务器获取最新的好友信息
			this.getFriendInfo(options.to)
		},
		onPullDownRefresh(e) {
			this.loadMoreHistoryMessage();
		},
		onUnload() {
			//退出聊天页面之前，清空页面传入的监听器
			let imService = getApp().globalData.imService;
			if(imService) {
				imService.onNewPrivateMessageReceive =  (friendId, message)=> {};
			}
		},
		methods: {
            //渲染文本消息，如果包含表情，替换为图片
		    //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
            renderTextMessage(message) {
				return '<span class="text-content">' + message.payload.text + '</span>'
            },
            //像微信那样显示时间，如果有几分钟没发消息了，才显示时间
            //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
            renderMessageDate(message, index) {
                if (index === 0) {
                    return this.formatDate(message.timestamp)
                } else {
                    if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
                        return this.formatDate(message.timestamp)
                    }
                }
                return '';
            },
	
			sendMessage(message){
            	let toId = message.to.id;
				let imService = getApp().globalData.imService;
            	let localHistory = imService.getPrivateMessages(toId);
				localHistory.push(message);
				console.log(JSON.stringify(message))
				this.goEasy.im.sendMessage({
					message: message,
					onSuccess: function (message) {
						console.log("发送成功.", message);
					},
					onFailed: function (error) {
						console.log("发送失败:",error);
					}
				});
			},
			sendTextMessage() {//发送消息
				if (this.content.trim() !== '') {
					let body = this.content;
					if(this.content.length >= 50){
						body = this.content.substring(0,30)+"...";
					}
					let textMessage = this.goEasy.im.createTextMessage({
						text: this.content,
						to : {
							id : this.friend.uuid,
							type : this.GoEasy.IM_SCENE.PRIVATE,
							data : {
								name:this.friend.name,
								avatar:this.friend.avatar
							}
						}
					});
					this.sendMessage(textMessage);
				}
				this.scrollToBottom();
				this.content = "";
			},
			loadMoreHistoryMessage() {//历史消息
				let self = this;
				let lastMessageTimeStamp = Date.now();
				let lastMessage = this.messages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				let currentLength = this.messages.length;
				this.goEasy.im.history({
					userId: self.friend.uuid,
					lastTimestamp: lastMessageTimeStamp,
					onSuccess: function (result) {
						//获取本地记录
						let imService = getApp().globalData.imService;
						let localHistory = imService.getPrivateMessages(self.friend.uuid);
						//添加加载的记录到本地记录尾部
						let messages = result.content;
						for (let i = messages.length - 1; i >= 0; i--) {
							localHistory.unshift(messages[i]);
						}
						if (localHistory.length === currentLength) {
							self.allHistoryLoaded = true;
						}
						self.messages = localHistory;
						uni.stopPullDownRefresh();
					},
					onFailed: function (error) {
						//获取失败
						if(error.code === 401){
							console.log("获取历史消息失败,默认不开通，付费应用，可以在我的应用->查看详情，高级功能里自助开通");
						}else{
							console.log("获取历史消息失败, code:" + error.code + ",错误信息:" + error.content);
						}
						uni.stopPullDownRefresh();
					}
				});
			},
			messageInputFocusin () {
			
			},
			scrollToBottom () {
				this.$nextTick(function(){
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration : 10
					})
				});
			},
			markPrivateMessageAsRead (friendId) {
				this.goEasy.im.markPrivateMessageAsRead({
					userId: friendId,
					onSuccess: function () {
						console.log('标记为已读成功')
					},
					onFailed: function (error) {
						console.log(error);
					}
				});
			},
            // 获取朋友消息
			getFriendInfo(friendId){
				let imService = getApp().globalData.imService
				this.$api.getUserInfoById(friendId).then(res=>{

			        this.friend = {
			        	"uuid": friendId + '',
			        	"name": res.nickName,
			        	"avatar": this.getImgUrl(res.avatar)
			        }
                    
			        this.messages = imService.getPrivateMessages(friendId)
				
			        uni.setNavigationBarTitle({
			        	title : this.friend.name
			        });

			        //监听新消息
			        imService.onNewPrivateMessageReceive =  (friendId, message)=> {
			        	if (friendId === this.friend.uuid) {
                            //聊天时，收到消息标记为已读
			        		this.markPrivateMessageAsRead(friendId);
			        		//收到新消息，是滚动到最底部
			        		this.scrollToBottom()
			        	}
			        };
			        //每次进入聊天页面，总是滚动到底部
			        this.scrollToBottom();
			        
			        //收到的消息设置为已读
			        if(this.messages.length !==0){
			        	this.markPrivateMessageAsRead(friendId);
			        }
				})
			}
		}
	}
</script>

<style>
	.chatInterface{

	}
	.chatInterface .scroll-view{
		padding-left: 20rpx;
		padding-right: 20rpx;
		box-sizing: border-box;
		-webkit-overflow-scrolling: touch;
		padding-bottom: 120rpx;
	}
	.chatInterface .scroll-view .all-history-loaded{
		font-size: 24rpx;
		height: 90rpx;
		line-height: 90rpx;
		width: 100%;
		text-align: center;
		color: grey;
	}

	.chatInterface .scroll-view .message-item{
		max-height: 400rpx;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		overflow: hidden;
		display: flex;
	}
	.chatInterface .scroll-view .message-item.self{
		overflow: hidden;
		display: flex;
		justify-content: flex-start;
		flex-direction: row-reverse;
	}
	.chatInterface .scroll-view .message-item .avatar{
		width: 80rpx;
		height: 80rpx;
		margin-right:20rpx;
		flex-shrink: 0;
		flex-grow: 0;
	}

	.chatInterface .scroll-view .message-item .avatar image{
		border-radius: 50%;
		width: 100%;
		height: 100%;
	}

	.chatInterface .scroll-view .message-item.self .avatar{
		margin-left: 20rpx;
		margin-right: 0;
	}


	.chatInterface .scroll-view .content{
		font-size: 34rpx;
		line-height: 44rpx;
		max-height: 400rpx;
		display: flex;
		align-items: center;
		justify-content: right;
		text-align: right;
	}
	.chatInterface .scroll-view .content .image-content{
		padding: 16rpx;
		border-radius: 12rpx;
		width: 300rpx;
		height: 300rpx;
	}
	.chatInterface .scroll-view .content .text-content{
		padding: 16rpx;
		border-radius: 12rpx;
		color: #ffffff;
		background:#618DFF;
		word-break: break-all;
		text-align: left;
		vertical-align: center;
		display: block;
	}
	.chatInterface .scroll-view .content .text-content img{
		width: 50rpx;
		height: 50rpx;
	}
	.chatInterface .scroll-view .content .pending{
		background: url("../../static/images/pending.gif") no-repeat center;
		background-size: 30rpx;
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
		flex-grow: 0;
		flex-shrink: 0;
	}

	.chatInterface .scroll-view .content .send-fail{
		background: url("../../static/images/failed.png") no-repeat center;
		background-size: 30rpx;
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
		flex-grow: 0;
		flex-shrink: 0;
	}

	.chatInterface .action-box{
		display: flex;
		backdrop-filter: blur(0.27rpx);
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		flex-direction: column;
		background-color: #FFFFFF;
	}
	.chatInterface .action-box .action-top{
		display: flex;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		backdrop-filter: blur(0.27rem);
		height: 100rpx;
		background:#FAFAFA;
		width: 100%;
	}

	.chatInterface .action-box .action-top .message-input{
		border-radius: 12rpx;
		background: #EFEFEF;
		height: 80rpx;
		margin-left: 40rpx;
	}
	.chatInterface .action-box .action-top .message-input input{
		width: 580rpx;
		height: 80rpx;
		line-height: 80rpx;
		padding-left: 20rpx;
		font-size: 28rpx;
	}
	.chatInterface .action-box .action-top .send-message-btn{
		font-size: 30rpx;
		width: 80rpx;
		line-height: 80rpx;
		color:#82868E ;
		margin-left: 20rpx;
	}
	
	.uni-toast{
		background-color: #ffffff!important;
	}
	.time-lag{
		font-size: 20rpx;
		text-align: center;
	}

</style>
